package 力扣._82_删除排序链表中的重复元素2;

import 力扣.公用数据结构.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        // 加头结点
        ListNode tHead = new ListNode(-1000, head);
        ListNode pre = tHead, p = tHead.next;
        while(p!=null){
            // 找到和p同值的最右边节点的下一个
            ListNode r = p;
            while(r!=null && r.val==p.val) r = r.next;
            if(r!=p){   // 存在重复节点，需删除
                pre.next = r;
                p = r;
            }else{
                pre = p;
                p = p.next;
            }
        }
        return tHead.next;
    }
}